<script setup>
import { ref } from 'vue'
import axios from "axios";
import { ElMessage } from "element-plus";

// 弹窗是否可见
const visible = ref(false)
const dialogTitle = ref('')
const mode = ref('add')

// 表单数据
const form = ref({
  roleName: '',
  roleCode: '',
  roleDesc: '',
  roleStatus: 1
})

// 校验规则
const rules = {
  roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  roleCode: [{ required: true, message: '请输入角色码', trigger: 'blur' }],
  roleDesc: [{ required: true, message: '请输入职位描述', trigger: 'blur' }]
}

const formRef = ref(null)

// 打开弹窗
const open = (actionMode, row = null) => {
  mode.value = actionMode
  visible.value = true
  dialogTitle.value = actionMode === 'add' ? '新增角色' : '编辑角色'

  if (actionMode === 'edit' && row) {
    form.value = { ...row }
  } else {
    form.value = {
      roleName: '',
      roleCode: '',
      roleDesc: '',
      roleStatus: 1
    }
  }
}

const handleCancel = () => {
  visible.value = false
}

const emit = defineEmits(['success'])
const handleSave = () => {
  formRef.value.validate(valid => {
    if (!valid) return
    const api = mode.value === 'add' ? '/role/addNewRole' : '/role/updateRole'
    axios.post(api, form.value).then(() => {
      ElMessage.success(mode.value === 'add' ? '添加成功' : '编辑成功')
      visible.value = false
      emit('success')
    }).catch(() => {
      ElMessage.error(mode.value === 'add' ? '添加失败' : '编辑失败')
    })
  })
}

defineExpose({ open })
</script>

<template>
  <el-dialog v-model="visible" :title="dialogTitle" width="500px">
    <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="100px"
        label-position="left"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="form.roleName" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item label="角色码" prop="roleCode">
        <el-input v-model="form.roleCode" placeholder="请输入角色码" />
      </el-form-item>
      <el-form-item label="职位描述" prop="roleDesc">
        <el-input
            type="textarea"
            v-model="form.roleDesc"
            placeholder="请输入职位描述"
            :autosize="{ minRows: 3, maxRows: 6 }"
        />
      </el-form-item>
      <el-form-item label="启用">
        <el-switch v-model="form.roleStatus" :active-value="1" :inactive-value="0" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
/* 防止标签或输入框换行，保持整洁 */
.el-form-item__label {
  white-space: nowrap;
}
</style>
